<template>
    <div class="filter">
        <div class="filter-item">
            <label for="">所属单位：</label>
            <el-select
                v-model="searchForm.depId"
                class="m-2"
                placeholder="请选择所属单位"
                style="width: 145px"
                :disabled="localTypeUnit != '1'"
            >
                <el-option
                    v-for="item in depIdList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>
        <div class="filter-item">
            <label for="">值班日期：</label>
            <el-date-picker
                style="width: 260px"
                v-model="searchForm.dateTime"
                type="daterange"
                unlink-panels
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :size="'default'"
                :shortcuts="shortcuts"
            />
        </div>
        <div class="filter-item">
            <label for="">状态：</label>
            <el-select
                v-model="searchForm.status"
                class="m-2"
                placeholder="请选择状态"
                style="width: 145px"
            >
                <el-option
                    v-for="item in statusList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
            </el-select>
        </div>
        <div class="filter-item">
            <el-button
                size="default"
                type="primary"
                @click="search"
            >查询</el-button>
            <el-button
                size="default"
                type="primary"
                @click="reset"
            >重置</el-button>
            <el-button
                size="default"
                type="success"
                @click="exportData"
            >导出</el-button>
        </div>
    </div>

    <div class="filter">
        <div class="filter-item">
            <el-button
                type="primary"
                @click="handleAdd('add')"
            >新增</el-button>
        </div>
    </div>
    <el-table
        :data="tableData"
        style="width: 100%"
        id="inspectionTask"
    >
        <el-table-column
            type="index"
            label="序号"
            width="55"
        />
        <el-table-column
            prop="depId"
            label="所属单位"
        >
            <template #default="scope">
                {{ depNameTranslate(scope.row.depId) }}
            </template>
        </el-table-column>
        <el-table-column
            prop="onDutyDate"
            label="值班日期"
        />
        <el-table-column
            prop="fromClassName"
            label="班次"
        />
        <el-table-column
            prop="fromUserName"
            label="交班人"
        />
        <el-table-column
            prop="fromSubmitTime"
            label="交班时间"
        />
        <el-table-column
            prop="status"
            label="状态"
        >
            <template #default="scope">
                {{
                    scope.row.status == "0"
                        ? "待交班"
                        : scope.row.status == "10"
                        ? "待接班"
                        : scope.row.status == "90"
                        ? "已确认"
                        : ""
                }}
            </template>
        </el-table-column>
        <el-table-column
            prop="toUserName"
            label="接班人"
        />
        <el-table-column
            prop="toConfirmTime"
            label="接班时间"
        />
        <el-table-column
            fixed="right"
            label="操作"
            width="190"
        >
            <template #default="scope">
                <el-button
                    text
                    type="primary"
                    size="small"
                    style="margin-left: 0"
                    @click="itemDetail(scope.row, 'detail')"
                >
                    详情
                </el-button>
                <el-button
                    text
                    type="primary"
                    size="small"
                    style="margin-left: 0"
                    :disabled="scope.row.status != '0'"
                    @click="handleAdd('edit', scope.row)"
                >
                    交班
                </el-button>
                <el-button
                    text
                    type="primary"
                    size="small"
                    style="margin-left: 0"
                    @click="itemDetail(scope.row, 'jb')"
                    :disabled="scope.row.status != '10'"
                >
                    接班
                </el-button>
                <el-button
                    text
                    type="primary"
                    size="small"
                    style="margin-left: 0"
                    @click="optionRecord(scope.row)"
                >
                    操作记录
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="searchForm.pageNo"
        v-model:page-size="searchForm.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="paginationStyle"
    />
    <el-dialog
        v-model="recordListVisible"
        title="操作记录"
        width="1000"
    >
        <div class="filter">
            <div class="filter-item">
                <label for="">操作时间：</label>
                <el-date-picker
                    style="width: 240px"
                    v-model="recordTime"
                    type="daterange"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :size="'default'"
                    :shortcuts="shortcuts"
                />
            </div>
            <div class="filter-item">
                <el-button
                    size="default"
                    type="warning"
                    @click="searchRecord(currentRowRecord)"
                >查询</el-button>
            </div>
        </div>
        <el-table
            :data="recordList"
            style="width: 100%"
        >
            <el-table-column
                prop="operationType"
                label="操作类型"
            />
            <el-table-column
                prop="createTime"
                label="操作时间"
                width="160"
            />
            <el-table-column
                prop="comment"
                label="操作内容"
                width="560"
            />
            <el-table-column
                prop="operationRealname"
                label="操作人"
            />
        </el-table>
        <el-pagination
            v-model:current-page="recordPageNo"
            v-model:page-size="recordPageSize"
            layout="total, prev, pager, next, jumper"
            :total="totalRecord"
            @size-change="handleSizeChangeRecord"
            @current-change="handleCurrentChangeRecord"
            class="paginationStyle"
        />
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="recordListVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog
        v-model="adjustVisible"
        :title="currentPublishType == 'add' ? '新增' : '交班'"
        width="850"
    >
        <el-form
            label-width="120"
            ref="changeOfDutyRuleFormRef"
            :model="changeOfDutyRuleForm"
            :rules="rules"
            class="demo-ruleForm"
            status-icon
            :inline="true"
        >
            <el-form-item
                label="所属单位："
                prop="depId"
                required
            >
                <el-select
                    v-model="changeOfDutyRuleForm.depId"
                    class="m-2"
                    placeholder="请选择所属单位"
                    style="width: 250px"
                    :disabled="localTypeUnit != '1'"
                >
                    <el-option
                        v-for="item in newDepIdList"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item
                label="值班日期："
                prop="onDutyDate"
                required
            >
                <el-date-picker
                    v-model="changeOfDutyRuleForm.onDutyDate"
                    type="date"
                    style="width: 250px"
                    format="YYYY-MM-DD"
                />
            </el-form-item>

            <el-form-item
                label="当班班次："
                prop="fromClassId"
                required
            >
                <el-select
                    v-model="changeOfDutyRuleForm.fromClassId"
                    :placeholder="`请选择`"
                    style="width: 250px"
                >
                    <el-option
                        :label="item.label"
                        :value="item.value"
                        v-for="item in typeList"
                        :key="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item
                label="接班班次："
                prop="toClassId"
                required
            >
                <el-select
                    v-model="changeOfDutyRuleForm.toClassId"
                    :placeholder="`请选择`"
                    style="width: 250px"
                >
                    <el-option
                        :label="item.label"
                        :value="item.value"
                        v-for="item in typeList"
                        :key="item.value"
                    />
                </el-select>
            </el-form-item>

            <el-form-item style="
                    margin-right: 0;
                    padding: 0 46px 0 25px;
                    width: 100%;
                    box-sizing: border-box;
                ">
                <el-table
                    :data="changeOfDutyRuleForm.tourDetailList"
                    style="width: 100%"
                    border
                >
                    <el-table-column
                        label="序号"
                        type="index"
                        width="60"
                    />
                    <el-table-column
                        prop="tourTime"
                        label="巡检时间"
                        width="180"
                    >
                        <template #default="scope">
                            <el-time-select
                                v-model="scope.row.tourTime"
                                style="width: 140px"
                                start="00:00"
                                step="00:30"
                                end="23:00"
                                placeholder="请选择"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="tourContent"
                        label="巡检内容"
                    >
                        <template #default="scope">
                            <el-input
                                v-model="scope.row.tourContent"
                                placeholder="请输入巡检内容"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="right"
                        label="操作"
                        width="120"
                    >
                        <template #default="scope">
                            <el-button
                                link
                                type="primary"
                                size="small"
                                @click="changeClassesHandleAdd('add')"
                            >
                                新增
                            </el-button>
                            <el-button
                                link
                                type="primary"
                                size="small"
                                @click="
                                    changeClassesHandleDelete(
                                        scope.row,
                                        scope.$index,
                                        'add'
                                    )
                                "
                                :disabled="
                                    changeOfDutyRuleForm.tourDetailList
                                        .length == 1
                                "
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>

            <el-form-item
                label="工艺调控记录："
                prop="adjustControlRecord"
            >
                <el-input
                    type="textarea"
                    v-model="changeOfDutyRuleForm.adjustControlRecord"
                    style="width: 250px"
                    :rows="3"
                    placeholder="请填写"
                ></el-input>
            </el-form-item>
            <el-form-item
                label="设备情况与其他事宜："
                prop="other"
            >
                <el-input
                    type="textarea"
                    v-model="changeOfDutyRuleForm.other"
                    style="width: 250px"
                    :rows="3"
                    placeholder="请填写"
                ></el-input>
            </el-form-item>
            <el-form-item>
                <div
                    class="picture"
                    style="
                        display: flex;
                        flex-direction: column;
                        padding-left: 26px;
                    "
                >
                    <div>图片：</div>
                    <div>
                        <el-upload
                            v-model:file-list="changeOfDutyRuleForm.fileList"
                            action="#"
                            :http-request="
                                (file) => {
                                    httpRequest(file, index);
                                }
                            "
                            list-type="picture-card"
                            :on-remove="
                                (file) => {
                                    handleRemove(file, index);
                                }
                            "
                            :on-preview="handlePictureCardPreview"
                            accept=".png,.jpg"
                            :limit="3"
                        >
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </div>
                </div>
            </el-form-item>

            <el-form-item
                style="
                    margin-right: 0;
                    padding: 0 46px 0 25px;
                    width: 100%;
                    box-sizing: border-box;
                "
                v-show="currentPublishType == 'edit'"
            >
                <div>
                    交接班任务<span style="font-size: 12px">（上一班发布）</span>
                </div>
                <br />
                <el-table
                    :data="changeOfDutyRuleForm.parentTaskDetailList"
                    style="width: 100%"
                    border
                >
                    <el-table-column
                        label="序号"
                        type="index"
                        width="60"
                    />
                    <el-table-column
                        prop="publishUsername"
                        label="发布人"
                        width="180"
                    >
                    </el-table-column>
                    <el-table-column
                        prop="tourContent"
                        label="内容"
                    >
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item style="
                    margin-right: 0;
                    padding: 0 46px 0 25px;
                    width: 100%;
                    box-sizing: border-box;
                ">
                <div>
                    发布任务<span style="font-size: 12px">（执行人为接班人）</span>
                </div>
                <el-table
                    :data="changeOfDutyRuleForm.taskDetailList"
                    style="width: 100%"
                    border
                >
                    <el-table-column
                        label="序号"
                        type="index"
                        width="60"
                    />
                    <!-- <el-table-column
                        prop="publishUsername"
                        label="发布人"
                        width="180"
                    /> -->
                    <el-table-column
                        prop="taskContent"
                        label="内容"
                    >
                        <template #default="scope">
                            <el-input
                                v-model="scope.row.taskContent"
                                placeholder="请填写"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column
                        fixed="right"
                        label="操作"
                        width="120"
                    >
                        <template #default="scope">
                            <el-button
                                link
                                type="primary"
                                size="small"
                                @click="changeClassesHandleAdd('taskDetailList')"
                            >
                                新增
                            </el-button>
                            <el-button
                                link
                                type="primary"
                                size="small"
                                @click="
                                    changeClassesHandleDelete(
                                        scope.row,
                                        scope.$index,
                                        'taskDetailList'
                                    )
                                "
                                :disabled="
                                    changeOfDutyRuleForm.taskDetailList
                                        .length == 1
                                "
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="adjustVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="saveRecord"
                    v-if="currentPublishType == 'edit'"
                > 保存 </el-button>
                <el-button
                    type="primary"
                    @click="submitRecord"
                >
                    {{ currentPublishType == 'add' ? '确认' : '交班' }}
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog
        v-model="itemDetailVisible"
        :title="itemDetailTitle"
        width="800"
    >
        <table class="changeClassesTable">
            <tr>
                <th>班次</th>
                <th colspan="4">值班情况</th>
            </tr>
            <tr>
                <td :rowspan="3 + tourContentListLen">
                    {{ itemDetailData.fromClassName }}
                </td>
                <td>巡视时间</td>
                <td colspan="2">巡视情况</td>
                <td
                    :rowspan="2 + tourContentListLen"
                    style="text-align: left; vertical-align: top"
                >
                    工艺调控记录：{{ itemDetailData.adjustControlRecord }}
                </td>
            </tr>
            <tr
                v-for="item in itemDetailData.tourContentList"
                :key="item"
            >
                <td>{{ item.tourTime }}</td>
                <td colspan="2">{{ item.tourContent }}</td>
            </tr>
            <tr>
                <td
                    colspan="3"
                    style="text-align: left; vertical-align: top"
                >
                    设备情况与其他事宜：{{ itemDetailData.other }}
                </td>
            </tr>
            <tr>
                <td>交班人</td>
                <td>{{ itemDetailData.fromUserName }}</td>
                <td>接班人</td>
                <td>{{ itemDetailData.toUserName }}</td>
            </tr>
        </table>
        <div class="picture">
            <div>图片：</div>
            <div
                class="demo-image__preview"
                v-if="itemDetailData.fileList && itemDetailData.fileList.length > 0"
            >
                <el-image
                    v-for="item in itemDetailData.fileList"
                    :key="item.url"
                    style="width: 100px; height: 100px"
                    :src="item.url"
                    :zoom-rate="1.2"
                    :max-scale="7"
                    :min-scale="0.2"
                    :preview-src-list="itemDetailData.fileList"
                    :initial-index="4"
                    fit="cover"
                />
            </div>
            <div v-else>无</div>
        </div>
        <div>
            <div style="margin-top: 20px">交接班任务</div>
            <el-table
                :data="itemDetailData.taskDetailList"
                style="width: 100%; margin-top: 10px"
                border
            >
                <el-table-column
                    label="序号"
                    type="index"
                    width="60"
                />
                <el-table-column
                    prop="publishUsername"
                    label="发布人"
                >
                </el-table-column>
                <el-table-column
                    prop="taskContent"
                    label="任务内容"
                >
                </el-table-column>
            </el-table>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="itemDetailVisible = false">取消</el-button>
                <el-button
                    v-if="itemDetailType == 'jb'"
                    type="primary"
                    @click="pickUpClassesConfirm"
                >
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog
        v-model="dialogVisible"
        title="图片预览"
    >
        <img
            style="width: 100%"
            :src="dialogImageUrl"
            alt="Preview Image"
        />
    </el-dialog>
</template>

<script setup>
import schedulingHttp from "@/https/scheduling.js";
import userHttp from "@/https/user.js";
import Storage from "@/utils/storage.js"; // storage工具类，简单的封装
import { Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import moment from "moment";
import { onMounted, reactive, ref, watch } from "vue";
const nowTime = new Date().getTime();
const day = new Date().getDay();
const oneDayTime = 24 * 60 * 60 * 1000;
const inspContent = ref("");
const realName = ref(Storage.localGet("realName"));
const userId = ref(Storage.localGet("userId"));
let searchForm = reactive({
    depId: "",
    inspectionLevel: "",
    dateTime: [moment().add(-7, "day"), moment()],
    status: "",
    pageNo: 1,
    pageSize: 10,
});
const depIdList = ref([
    { label: "全部", value: "1" },
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const newDepIdList = ref([
    { label: "星沙厂", value: "2" },
    { label: "城西厂", value: "3" },
    { label: "城北厂", value: "4" },
    { label: "城南厂", value: "5" },
    { label: "城东厂", value: "6" },
]);
const depNameTranslate = (depId) => {
    let depName = "";
    depIdList.value.forEach((item) => {
        if (item.value == depId + "") {
            depName = item.label;
        }
    });
    return depName;
};
const inspectionLevelList = ref([
    { label: "全部", value: "" },
    { label: "一级", value: "一级" },
    { label: "二级", value: "二级" },
    { label: "三级", value: "三级" },
]);
const statusList = ref([
    { label: "全部", value: "" },
    { label: "待交班", value: "0" },
    { label: "待接班", value: "10" },
    { label: "已确认", value: "90" },
]);
const localTypeUnit = ref(Storage.localGet("depId"));
searchForm.depId = localTypeUnit.value;

const recordListVisible = ref(false);
const adjustVisible = ref(false);

const changeOfDutyRuleForm = reactive({
    id: "",
    depId: "",
    onDutyDate: "",
    fromClassId: "",
    toClassId: "",
    tourDetailList: [
        {
            tourContent: "",
            tourTime: "",
        },
        {
            tourContent: "",
            tourTime: "",
        },
        {
            tourContent: "",
            tourTime: "",
        },
        {
            tourContent: "",
            tourTime: "",
        },
    ],
    adjustControlRecord: "",
    other: "",
    fileList: [],
    fileListResList: [],
    imageIds: "",
    taskDetailList: [
        {
            publishUserID: userId.value,
            publishUsername: realName.value,
            taskContent: "",
        },
    ],
    parentTaskDetailList: []
});

const shortcuts = [
    {
        text: "本年",
        value: () => {
            return [
                moment().startOf("year"),
                moment().endOf("year"),
            ];
        },
    },
    {
        text: "本月",
        value: () => {
            return [
                moment().startOf("month"),
                moment().endOf("month"),
            ];
        },
    },
    {
        text: "下月",
        value: () => {
            return [
                moment().add(1, 'month').startOf("month"),
                moment().add(1, 'month').endOf("month"),
            ];
        },
    },
    {
        text: "本周",
        value: () => {
            return [
                moment().startOf("week"),
                moment().endOf("week"),
            ];
        },
    },
    {
        text: "下周",
        value: () => {
            return [
                moment().add(1, 'week').startOf("week"),
                moment().add(1, 'week').endOf("week"),
            ];
        },
    },
    {
        text: "本日",
        value: () => {
            return [
                moment(),
                moment(),
            ];
        },
    },
];
const shortcuts2 = [
    {
        text: "仅本月",
        value: () => {
            const now = new Date();
            const end = new Date(now.getFullYear(), now.getMonth() + 1, 0);
            const start = moment(new Date()).add(1, "day");
            return [start, end];
        },
    },
    {
        text: "本月及以后",
        value: () => {
            const now = new Date();
            const end = new Date(now.getFullYear(), now.getMonth() + 2, 0);
            const start = moment(new Date()).add(1, "day");
            return [start, end];
        },
    },
];
const disabledDate = (time) => {
    // 禁用今天之前的日期
    return time.getTime() < Date.now(); // 8.64e7 毫秒数代表一天
};
const updateTime = ref([
    // "2024-04-01",
    // "2024-04-30",
    moment(new Date()).add(1, "day"),
    new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0),
]);
let ruleForm = reactive({
    region: "",
    name: "",
    desc: "",
    continuous: "",
    value1: [],
    type11: "class",
    number: 1,
    dayNumber: 1,
    monthNumber: 1,
    weekNumber: "1",
    week: "Mon",
    inspectionType: 1,
});
const tableData = ref([]);
const adjustType = ref("巡检人员");
const inspectionType = ref("当日值班班组");
const inspectionUser = ref("");
const typeList = ref([]);
const adjustTime = ref(moment().format("YYYY-MM-DD"));
const adjustStatus = ref("100");

const classesShowList = ref([]);
// 查询班次信息
const getWorkClassQueryWorkClassShow = async (type, row) => {
    let params = {
        depId: changeOfDutyRuleForm.depId,
        classType: "1",
        isDelete: "0",
        pageNo: 1,
        pageSize: 1000,
    };
    const res = await schedulingHttp.workClassQueryWorkClass(params);
    if (res.data.code == 200) {
        res.data.data.records.forEach((item) => {
            item.label = item.className;
            item.shortLabel = item.classShortName + "";
            item.value = item.id + "";
            item.statusTrigger = false;
        });
        classesShowList.value = res.data.data.records;
        typeList.value = classesShowList.value;
    }
};
const classesAllList = ref([]);
// 查询班次信息
const getWorkClassQueryWorkClassAll = async (type, row) => {
    let params = {
        depId: "1",
        classType: "1",
        isDelete: "0",
        pageNo: 1,
        pageSize: 1000,
    };
    const res = await schedulingHttp.workClassQueryWorkClass(params);
    if (res.data.code == 200) {
        res.data.data.records.forEach((item) => {
            item.label = item.className;
            item.shortLabel = item.classShortName + "";
            item.value = item.id + "";
            item.statusTrigger = false;
        });
        classesAllList.value = res.data.data.records;
    }
};
const userList = ref([]);
const userQueryUserList = async (row) => {
    let params = {
        depId: changeOfDutyRuleForm.depId,
        isDelete: 0,
        pageNo: 1,
        pageSize: 10000,
    };
    const res = await userHttp.userQueryUserList(params);
    if (res.data.code == 200) {
        res.data.data.records.forEach((item) => {
            item.label = item.realName;
            item.value = item.id + "";
        });
        userList.value = res.data.data.records;
    }
};
const groupList = ref([]);
// 查询班组信息
const getWorkteamsQueryWorkTeams = async (row) => {
    let params = {
        depId: changeOfDutyRuleForm.depId,
        pageNo: 1,
        pageSize: 10000,
    };
    const res = await schedulingHttp.workteamsQueryWorkTeams(params);
    if (res.data.code == 200) {
        res.data.data.records.forEach((item) => {
            item.label = item.teamName;
            item.value = item.id;
        });
        groupList.value = res.data.data.records;
    }
};
const adjustStatusList = ref([
    { label: "未开始", value: "0" },
    { label: "进行中", value: "10" },
    { label: "已完成", value: "100" },
]);
const adjustList = ref([
    { label: "单次", value: "1" },
    { label: "每天", value: "2" },
]);
const currentAdjustRow = ref();
const ruleFormRef = ref();
const currentPublishType = ref("");

const dailyTaskRuleForm = reactive({
    id: "",
    depId: "",
    executor: "",
    executorMode: "",
    planEndTime: "",
    planStartTime: "",
    publishType: "",
    taskContent: "",
});

dailyTaskRuleForm.depId = localTypeUnit.value;

// ------------------------新增----------------------
const handleAdd = (type, row) => {
    currentPublishType.value = type;
    adjustVisible.value = true;
    getWorkClassQueryWorkClassShow(type, row);
    console.log(row, 'row')
    if (type == "edit") {
        changeOfDutyRuleForm.id = row.id + "";
        changeOfDutyRuleForm.depId = row.depId + "";
        changeOfDutyRuleForm.onDutyDate = row.onDutyDate + "";
        changeOfDutyRuleForm.fromClassId = row.fromClassId + "";
        changeOfDutyRuleForm.toClassId = row.toClassId + "";
        changeOfDutyRuleForm.tourDetailList = JSON.parse(row.tourContent);
        changeOfDutyRuleForm.adjustControlRecord = row.adjustControlRecord;
        changeOfDutyRuleForm.other = row.other;
        changeOfDutyRuleForm.taskDetailList = [
            ...row.taskDetailList
        ];
        changeOfDutyRuleForm.parentTaskDetailList = row.parentTaskDetailList;
        if (row.imageIds) {
            schedulingHttp
                .fileInfoGetByIds(row.imageIds)
                .then((response) => {
                    changeOfDutyRuleForm.fileList = response.data.data;
                    changeOfDutyRuleForm.fileListResList = response.data.data;
                });
        }
    } else {
        changeOfDutyRuleForm.id = "";
        changeOfDutyRuleForm.depId =
            localTypeUnit.value == "1" ? "" : localTypeUnit.value;
        changeOfDutyRuleForm.onDutyDate = "";
        changeOfDutyRuleForm.fromClassId = "";
        changeOfDutyRuleForm.toClassId = "";
        changeOfDutyRuleForm.tourDetailList = [
            {
                tourContent: "",
                tourTime: "",
            },
            {
                tourContent: "",
                tourTime: "",
            },
            {
                tourContent: "",
                tourTime: "",
            },
            {
                tourContent: "",
                tourTime: "",
            },
        ];
        changeOfDutyRuleForm.adjustControlRecord = "";
        changeOfDutyRuleForm.other = "";
        changeOfDutyRuleForm.taskDetailList = [
            {
                publishUserID: userId.value,
                publishUsername: realName.value,
                taskContent: "",
            },
        ];
    }
};
const rules = ref({
    depId: [{ required: true, message: "请输入", trigger: "blur" }],
    onDutyDate: [
        {
            required: true,
            message: "请选择",
            trigger: "blur",
        },
    ],
    fromClassId: [
        {
            required: true,
            message: "请选择",
            trigger: "blur",
        },
    ],
    toClassId: [
        {
            required: true,
            message: "请输入",
            trigger: "blur",
        },
    ],
    planStartTime: [
        {
            required: true,
            message: "请选择",
            trigger: "blur",
        },
    ],
    planEndTime: [
        {
            required: true,
            message: "请选择",
            trigger: "blur",
        },
    ],
    publishType: [
        {
            required: true,
            message: "请选择",
            trigger: "blur",
        },
    ],
});

// ------------------------发布----------------------
const submitInfo = () => {
    console.log(1);
    if (!ruleFormRef) return;
    ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            let params = {
                ...dailyTaskRuleForm,
            };
            params.planStartTime = moment(
                dailyTaskRuleForm.planStartTime
            ).format("YYYY-MM-DD HH:mm:ss");
            params.planEndTime = moment(dailyTaskRuleForm.planEndTime).format(
                "YYYY-MM-DD HH:mm:ss"
            );

            if (currentPublishType.value == "add") {
                const res = await schedulingHttp.dailyTaskPublish(params);
                if (res.data.code == 200) {
                    ElMessage({
                        type: "success",
                        message: "发布成功",
                    });
                    adjustVisible.value = false;
                    search();
                }
            } else {
                const res = await schedulingHttp.dailyTaskEditTask(params);
                if (res.data.code == 200) {
                    ElMessage({
                        type: "success",
                        message: "编辑成功",
                    });
                    adjustVisible.value = false;
                    search();
                }
            }
        }
    });
};
const activeName = ref("");

const handleClick = (name) => { };
const activeEq = ref({});
const currentTask = ref({});

// ------------------------交班弹窗----------------------
const changeOfDutyRuleFormRef = ref();
const changeClassesHandleAdd = (type) => {
    if (type == "add") {
        changeOfDutyRuleForm.tourDetailList.push({
            tourTime: "",
            tourContent: "",
        });
    } else if (type == "taskDetailList") {
        changeOfDutyRuleForm.taskDetailList.push({
            publishUserID: userId.value,
            publishUsername: realName.value,
            taskContent: "",
        });
    }
};
const changeClassesHandleDelete = (row, index, type) => {
    if (type == "add") {
        console.log(row, index);
        changeOfDutyRuleForm.tourDetailList.splice(index, 1);
    } else if (type == "taskDetailList") {
        console.log(row, index);
        changeOfDutyRuleForm.taskDetailList.splice(index, 1);
    }
};
const saveRecord = async () => {
    console.log(1);
    if (!changeOfDutyRuleFormRef) return;
    let imgids = [];
    if (changeOfDutyRuleForm.fileListResList.length > 0) {
        changeOfDutyRuleForm.fileListResList.forEach((m) => {
            imgids.push(m.id);
        });
        changeOfDutyRuleForm.imageIds = imgids.join(",");
    }
    let params = {
        ...changeOfDutyRuleForm,
        onDutyDate: moment(changeOfDutyRuleForm.onDutyDate).format(
            "YYYY-MM-DD"
        ),
    };
    changeOfDutyRuleFormRef.value.validate(async (valid, fields) => {
        const res = await schedulingHttp.handoverTaskSaveRecord(params);
        console.log(res, "res");
        if (res.data.code == "200") {
            ElMessage({
                message: "提交成功",
                type: "success",
            });
            search();
            adjustVisible.value = false;
        }
    });
};
const submitRecord = async () => {
    console.log(1);
    if (!changeOfDutyRuleFormRef) return;
    let imgids = [];
    if (changeOfDutyRuleForm.fileListResList.length > 0) {
        changeOfDutyRuleForm.fileListResList.forEach((m) => {
            imgids.push(m.id);
        });
        changeOfDutyRuleForm.imageIds = imgids.join(",");
    }
    let params = {
        ...changeOfDutyRuleForm,
        onDutyDate: moment(changeOfDutyRuleForm.onDutyDate).format(
            "YYYY-MM-DD"
        ),
    };
    changeOfDutyRuleFormRef.value.validate(async (valid, fields) => {
        if (currentPublishType.value == 'add') {
            const res = await schedulingHttp.handoverTaskSaveRecord(params);
            console.log(res, "res");
            if (res.data.code == "200") {
                ElMessage({
                    message: "新增成功",
                    type: "success",
                });
                search();
                adjustVisible.value = false;
            }
        } else {
            const res = await schedulingHttp.handoverTaskSubmitRecord(params);
            console.log(res, "res");
            if (res.data.code == "200") {
                ElMessage({
                    message: "提交成功",
                    type: "success",
                });
                search();
                adjustVisible.value = false;
            }
        }
    });
};
// ------------------------详情----------------------
const reportTaskDataList = ref([]);
const fileList = ref([]);
const itemDetailData = ref({});
const tourContentListLen = ref(0);
const itemDetailVisible = ref(false);
const itemDetailType = ref("");
const itemDetailTitle = ref("");
const itemDetail = async (row, type) => {
    itemDetailTitle.value = type == 'detail' ? '详情' : '接班'
    itemDetailVisible.value = true;
    currentTask.value = row;
    itemDetailType.value = type;
    const res = await schedulingHttp.handoverRecordGetById(row);
    if (res.data.code == "200") {
        res.data.data.tourContentList = JSON.parse(res.data.data.tourContent);
        if (res.data.data.tourContentList) {
            tourContentListLen.value = res.data.data.tourContentList.length || 0;
        }
        itemDetailData.value = res.data.data;
        if (res.data.data.imageIds) {
            schedulingHttp
                .fileInfoGetByIds(res.data.data.imageIds)
                .then((response) => {
                    itemDetailData.value.fileList = response.data.data;
                });
        }
    }
};
const pickUpClassesConfirm = async () => {
    const res = await schedulingHttp.handoverRecordToConfirm(
        itemDetailData.value
    );
    if (res.data.code == "200") {
        itemDetailVisible.value = false;
        ElMessage({
            type: "success",
            message: "提交成功",
        });
        search();
    } else {
        ElMessage({
            type: "error",
            message: "提交失败",
        });
    }
};
const uploadList = ref([]);

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handleRemove = (uploadFile, index) => {
    console.log(uploadFile, index);
    changeOfDutyRuleForm.fileListResList.forEach((m, n) => {
        if (uploadFile.id == m.id) {
            changeOfDutyRuleForm.fileListResList.splice(n, 1);
        }
    });
};

const handlePictureCardPreview = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url;
    dialogVisible.value = true;
};
const uploadImgCount = ref(0);
const httpRequest = (params, index) => {
    console.log(params, index, "httpRequest");
    uploadImgCount.value++;
    schedulingHttp.fileInfoUpload(params).then((res) => {
        if (res.data.code == 200) {
            console.log(res.data, "1111111");
            changeOfDutyRuleForm.fileListResList.push({
                fileName: res.data.data.fileName,
                url: res.data.data.url,
                id: res.data.data.id,
            });
            uploadImgCount.value--;
            ElMessage({
                type: "success",
                message: "上传成功",
            });
        }
    });
};
const reportTaskConfirm = async () => {
    if (uploadImgCount.value > 0) {
        ElMessage({
            type: "error",
            message: "请等待图片上传成功",
        });
        return;
    }
    let msgReportNoFinish = 0;
    let msgReportNoFinishList = [];
    reportTaskDataList.value.forEach((item) => {
        item.equipmentId = item.id;
        let imgids = [];
        if (item.fileList.length > 0) {
            item.fileList.forEach((m) => {
                imgids.push(m.id);
            });
            item.imageIds = imgids.join(",");
        } else {
            item.imageIds = "";
        }
    });

    if (msgReportNoFinish > 0) {
        console.log("每天完");
        let msgText = msgReportNoFinishList.join("\n");
        ElMessage({
            message: msgText,
            type: "warning",
        });
        return;
    }
    let params = {
        id: currentTask.value.id,
        detailList: reportTaskDataList.value,
        inspContent: inspContent.value,
    };
    const res = await schedulingHttp.dailyTaskReportDailyTask(params);
    if (res.data.code == "200") {
        itemDetailVisible.value = false;
        ElMessage({
            type: "success",
            message: "提交成功",
        });
        search();
    } else {
        ElMessage({
            type: "error",
            message: "提交失败",
        });
    }
};

// ------------------------查询----------------------
let total = ref(0);
const handleSizeChange = (val) => {
    searchForm.pageSize = val;
    search();
};
const handleCurrentChange = (val) => {
    searchForm.pageNo = val;
    search();
};
const search = async () => {
    let params = {
        ...searchForm,
        startTime: searchForm.dateTime[0]
            ? moment(searchForm.dateTime[0]).format("YYYY-MM-DD")
            : "",
        endTime: searchForm.dateTime[1]
            ? moment(searchForm.dateTime[1]).format("YYYY-MM-DD")
            : "",
    };
    const res = await schedulingHttp.handoverRecordRecordList(params);
    if (res.data.code == 200) {
        tableData.value = res.data.data.records;
        total.value = res.data.data.total;
    }
};
const reset = () => {
    searchForm.depId = localTypeUnit.value;
    searchForm.inspectionLevel = "";
    searchForm.dateTime = [moment().add(-7, "day"), moment()];
    searchForm.status = "";
    searchForm.pageNo = 1;
    searchForm.pageSize = 10;
    search();
};
// ------------------------记录----------------------
const recordTime = ref([]);
const recordList = ref([]);
const currentRowRecord = ref();
const optionRecord = async (row) => {
    recordListVisible.value = true;
    currentRowRecord.value = row;
    recordTime.value[0] = moment().format("YYYY-MM-DD");
    recordTime.value[1] = moment().add(1, "day").format("YYYY-MM-DD");
    searchRecord(currentRowRecord.value);
};
const recordPageNo = ref(1);
const recordPageSize = ref(10);

let totalRecord = ref(0);
const handleSizeChangeRecord = (val) => {
    recordPageSize.value = val;
    searchRecord(currentRowRecord.value);
};
const handleCurrentChangeRecord = (val) => {
    recordPageNo.value = val;
    searchRecord(currentRowRecord.value);
};
const searchRecord = async (row) => {
    let params = {
        businessId: row.id,
        operationType: "",
        businessType: "交班记录",
        startTime:
            recordTime.value.length > 0
                ? moment(recordTime.value[0]).format("YYYY-MM-DD")
                : "",
        endTime:
            recordTime.value.length > 0
                ? moment(recordTime.value[1]).format("YYYY-MM-DD")
                : "",
        pageNo: recordPageNo.value,
        pageSize: recordPageSize.value,
    };
    const res = await schedulingHttp.operationRecordsQueryOperationRecords(
        params
    );
    if (res.data.code == 200) {
        recordList.value = res.data.data.records;
        totalRecord.value = res.data.data.total;
    }
};

const exportData = async () => {
    let params = {
        ...searchForm,
        startTime: searchForm.dateTime[0]
            ? moment(searchForm.dateTime[0]).format("YYYY-MM-DD")
            : "",
        endTime: searchForm.dateTime[1]
            ? moment(searchForm.dateTime[1]).format("YYYY-MM-DD")
            : "",
    };
    schedulingHttp.handoverRecordExportRecord(params).then((response) => {
        console.log(response);
        const content = response.data;
        const blob = new Blob([content], { type: "application/zip" });
        let fileName = `交接班记录.zip`;
        if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            elink.download = fileName;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
        }
    });
}
watch(
    () => changeOfDutyRuleForm.depId,
    (val) => {
        getWorkClassQueryWorkClassShow();
        getWorkteamsQueryWorkTeams();
        userQueryUserList();
        getWorkClassQueryWorkClassAll();
    },
    { deep: true }
);
// watch(
//     () => dailyTaskRuleForm.executorMode,
//     (val) => {
//         console.log(val, "value");
//         if (val == "当日值班班组") {
//             typeList.value = classesShowList.value;
//         } else if (val == "固定班组") {
//             typeList.value = groupList.value;
//         } else if (val == "固定人员") {
//             typeList.value = userList.value;
//         }
//     },
//     { deep: true }
// );
onMounted(() => {
    getWorkClassQueryWorkClassShow();
    getWorkteamsQueryWorkTeams();
    userQueryUserList();
    search();
});
</script>

<style scoped lang="less">
.filter {
    flex-wrap: wrap;
    display: flex;
    flex-direction: row;
    align-items: center;
    .filter-item {
        margin: 0 15px 15px 0px;
        display: flex;
        flex-direction: row;
        align-items: center;
        label {
            font-size: 14px;
            color: #333;
            display: inline-block;
            white-space: nowrap;
        }
    }
}
.reportLabel {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 60px;
    p {
        line-height: 1.5;
    }
}
:deep .el-dialog__body {
    padding: 20px !important;
}
:deep .el-tabs__item {
    height: 100px !important;
}
:deep .el-upload {
    width: 100px !important;
    height: 100px !important;
}
:deep .el-upload-list__item.is-ready {
    width: 100px !important;
    height: 100px !important;
}
:deep .el-upload-list__item.is-success {
    width: 100px !important;
    height: 100px !important;
}

.scopeBox {
    min-width: 130px;
}
.dialogTitle {
    line-height: 2;
    margin-bottom: 10px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
}
.projectBox {
    padding: 0 20px;
    p {
        font-size: 16px;
        margin-bottom: 10px;
    }
    .urlBox {
        // display: flex;
        // flex-direction: row;
        margin-top: 30px;
    }
    ul li {
        line-height: 1.5;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
    }
}

.changeClassesTable {
    border-collapse: collapse;
    border: 1px solid #ccc;
    width: 100%;
    font-size: 0.28rem;
    text-align: center;
    th {
        height: 30px;
        font-size: 14px;
        border-bottom: 1px solid #ccc;
        border-right: 1px solid #ccc;
        background: #eee;
    }
    tr {
        width: 100%;
        line-height: 1.5;
        font-size: 14px;
        border-bottom: 1px solid #ccc;
        border-right: 1px solid #ccc;
        td {
            text-align: center;
            line-height: 30px;
            min-width: 100px;
            height: 30px;
            font-size: 14px;
            border-bottom: 1px solid #ccc;
            border-right: 1px solid #ccc;
        }
    }
}
.picture {
    margin-top: 20px;
    display: flex;
    flex-direction: row;
}
</style>